package com.example.mychat.controller;

import com.example.mychat.component.OnLineUserMapper;
import com.example.mychat.model.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Component
public class WebSocketController extends TextWebSocketHandler {

    @Autowired
    private OnLineUserMapper onLineUserMapper;
    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Autowired
    private MessageMapper messageMapper;
    private ObjectMapper objectMapper=new ObjectMapper();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("websocket连接成功");
        User user = (User)session.getAttributes().get("User");
        if(user==null){
            return;
        }
        //把这个键值对给存起来
        onLineUserMapper.online(user.getId(), session);

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到消息" + message.toString());
        //先获取当前用户信息，在进行转发
        User user = (User) session.getAttributes().get("User");
        if(user==null){
            System.out.println("WebSocket获得的user为null,未登录");
            return;
        }
        //对请求进行解析，把json格式的字符串转换成一个java中的对象
        MessageRequest request = objectMapper.readValue(message.getPayload(),MessageRequest.class);
        if(request.getType().equals("message")){
            //进行消息转发
            transferMessage(user,request);
        }else {
            System.out.println("request.type有误" + message.getPayload());
        }


    }

    //实际消息的转发
    private void transferMessage(User fromuser, MessageRequest request) throws IOException {
        //先构造一个待转发的相应对象
        MessageResponse response = new MessageResponse();
        response.setType("message");
        response.setFromId(fromuser.getId());
        response.setFromName(fromuser.getUsername());
        response.setContent(request.getContent());
        response.setSessionId(request.getSessionId());
        //把这个java对象转换成json字符串
        String respJson = objectMapper.writeValueAsString(response);
        System.out.println("转换成json字符串的java对象: " + respJson);

        //根据请求中的sessionId，获取到这个MessageSession里有哪些用户，通过查数据库
        List<Friend> friends = messageSessionMapper.getUserBySessionId(request.getSessionId(), fromuser.getId());
         //数据库的查询方法没有包含自己，要重新构建
        Friend myself = new Friend();
        myself.setFriendId(fromuser.getId());
        myself.setFriendName(fromuser.getUsername());
        System.out.println("打印出我自己的个人信息 :" + myself);
        friends.add(myself);

        for (Friend friend: friends) {
            //知道每一个用户的userId，通过OnlineUserMessage查询对应的WebSocketSession
            //来进行发送消息
            System.out.println("打印出每一个friend的信息 :" + friend);
            WebSocketSession webSocketSession = onLineUserMapper.getSession(friend.getFriendId());
            System.out.println("webSocketSession的值是 ： " + webSocketSession);
            if(webSocketSession==null){
                //如果用户未在线就不发送
                continue;
            }
            System.out.println("还没有发送");
            webSocketSession.sendMessage(new TextMessage(respJson));
            System.out.println("已经成功发送");
        }
        //转发的消息写入数据库中，用户上线后可以通过历史消息拿到数据
        Message message = new Message();
        message.setFromId(fromuser.getId());
        message.setSessionId(request.getSessionId());
        message.setContent(request.getContent());
        messageMapper.add(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常"+ exception.toString());
        User user = (User)session.getAttributes().get("User");
        if(user==null){
            return;
        }
        //用户下线
        onLineUserMapper.offline(user.getId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭"+ status.toString());
        User user = (User)session.getAttributes().get("User");
        if(user==null){
            return;
        }
        //用户下线
        onLineUserMapper.offline(user.getId(), session);
    }
}
